#include "GameLib.h"

void CSound::SoundInit()
{
	if (!alutInit (NULL, NULL))
		GetErrAL();
	alListenerf(AL_GAIN, 2);
	SoundList();
}

void CSound::SoundList()
{
	OpenSound("data/sounds/music.wav", 1, 0, 0.5);
	SetPosition(1, 0.0f, 0.0f, 0.0f);
	PlaySound(1);
}

void CSound::RandPlay()
{
	float rand_time = 0.0f;
	Uint32 timer = SDL_GetTicks(); // ms -> 1 minute = 3600 ms
	int max_time = 3600 + timer;
	float track =0;
	track = (rand()% (2 - 1 + 1)) + 1; // (rand() % (max - min + 1)) + min

	rand_time = (rand()% (max_time - timer + 1)) + timer;

	if (rand_time == SDL_GetTicks())
		if(track == 1)
			PlaySound(7);
		else PlaySound(8);

}


void CSound::OpenSound(const char* track, int index, int loop, float volume)
{
	
	buffer = alutCreateBufferFromFile (track);
	if (buffer == AL_NONE)
    {
		GetErrAL();
    }

	//ALfloat mPos[3] = {x, y, z};
	alGenSources (1, &source[index]);
	alSourcei (source[index], AL_BUFFER, buffer);
	alSourcef (source[index], AL_PITCH,    1.0f);
	alSourcef (source[index], AL_GAIN,    volume);
	//alSourcefv(source[index], AL_POSITION, mPos);
	//alSourcefv(source, AL_VELOCITY,  1.0f);
	alSourcei(source[index], AL_LOOPING, loop);
	GetErrAL();
}

bool CSound::PlaySound(int index)
{
	alSourcePlay (source[index]);
	return true;
}

bool CSound::StopSound(int index)
{
	alSourceStop(source[index]);
	return true;
}

void CSound::CloseSound()
{
	for(int i =0; i < 10; ++i)
	{
		alSourceStop(source[i]);
		if (alIsSource(source[i])) alDeleteSources(1, &source[i]);
	}
}
